import { reqOrderAddress, reqOrderDetail, reqBuyNow, reqSubmitOrder, reqAdvancePay } from '@/api/order'
import timeFormat from '@/utils/timeFormat'
import Schema from 'async-validator'
import { debounce } from 'miniprogram-licia'

Page({
  // 页面的初始数据
  data: {
    orderAddress: {}, //订单地址
    orderDetail: {},
    blessing: '',
    showTime: false, //
    deliveryDate: '', //送达时间
    minDate: new Date().getTime()
  },

  // 收货地址
  async getOrderAddress() {
    // 渲染的是更改后地址还是默认地址
    const res = await reqOrderAddress()
    if (res.code === 200) {
      this.setData({
        orderAddress: res.data
      })
    }
    this.receiveAddress()
  },

  // 接收更新后的地址
  receiveAddress() {
    const { orderAddress, newOrderAddress } = this.data
    // 加上空判断，避免初始状态下未添加收货地址报错
    // if (JSON.stringify(orderAddress) === '{}' || !reFlag) return
    // const eventChannel = this.getOpenerEventChannel()
    // eventChannel.on('updateOrderAddress', (res) => {
    //   this.setData({
    //     orderAddress: res
    //   })
    // })
    // 方式二：接收更新后的地址（解决了页面调转上限问题）
    // 初始收货地址为空或没更新收货地址都不进行下一步
    if (JSON.stringify(orderAddress) === '{}' || !newOrderAddress) return
    this.setData({
      orderAddress: newOrderAddress
    })
  },

  // 详情
  async getOrderDetail() {
    const { goodsId, blessing } = this.data
    // 区分是从详情页立即购买还是从购物车点击购买
    const res = goodsId ? await reqBuyNow({ goodsId, blessing }) : await reqOrderDetail()
    if (res.code === 200) {
      // 默认返回第一个填了祝福语的商品
      const hasBlessing = res.data.cartVoList.find((item) => item.blessing !== '' && item.blessing !== null)
      this.setData({
        orderDetail: res.data,
        blessing: hasBlessing ? hasBlessing.blessing : ''
      })
    }
  },
  goEmptyAddressList() {
    wx.navigateTo({
      url: '/modules/settingsModule/pages/address/address-list/address-list'
    })
  },

  goAddressList(e) {
    const { id } = e.currentTarget.dataset
    wx.navigateTo({
      url: `/modules/settingsModule/pages/address/address-list/address-list?flag=1&id=${id}`
    })
  },

  onClickPicker() {
    this.setData({ showTime: true })
  },

  // 时间选择器
  confirmTimePicker(e) {
    const selectedTime = e.detail
    const deliveryDate = timeFormat(selectedTime)
    this.setData({ deliveryDate, showTime: false })
  },

  onCloseTimePicker() {
    this.setData({ showTime: false })
  },

  onClose() {
    this.setData({ showTime: false })
  },

  // 提交订单
  onSubmitOrder: debounce(async function () {
    // 先收集参数，校验通过后再调接口
    const { orderAddress, orderDetail, blessing, deliveryDate } = this.data
    const orderParams = {
      buyName: orderAddress?.name,
      buyPhone: orderAddress?.phone,
      cartList: orderDetail.cartVoList,
      deliveryDate: deliveryDate,
      remarks: blessing,
      userAddressId: orderAddress?.id
    }
    const validateRes = await this.validateRules(orderParams)
    if (!validateRes) return
    const res = await reqSubmitOrder(orderParams)
    if (res.code === 200) {
      // 将后端返回的订单编号挂载到页面
      this.orderNo = res.data
      // 调预支付
      this.advancePay()
    }
  }, 300),

  // 定义校验参数规则
  validateRules(params) {
    const rules = {
      userAddressId: [{ required: true, message: '请选择收货地址' }],
      deliveryDate: [{ required: true, message: '请选择送达时间' }]
    }
    // 创建实例，传入校验规则
    const validator = new Schema(rules)
    // 验证，返回个promise函数
    return new Promise((resolve) => {
      validator.validate(params, (error) => {
        if (error) {
          wx.toast({ title: error[0].message })
          resolve(false)
        } else {
          resolve(true)
        }
      })
    })
  },

  // 预支付
  async advancePay() {
    try {
      const payRes = await reqAdvancePay(this.orderNo)
      if (payRes.code === 200) {
        // todo:个人主体暂时无法接入微信支付入口，需要迁移企业主体，略过
        // const res = await wx.requestPayment(payRes.data)
        // if (res.errMsg === 'requestPayment:ok') {
        //   wx.toast({ title: '支付成功' })
        // }
        // todo：先做跳转，默认支付成功
        wx.redirectTo({
          url: '/modules/orderModule/pages/order/order-list/order-list',
          success: () => {
            wx.toast({
              title: '支付成功',
              icon: 'success'
            })
          }
        })
      }
    } catch (error) {
      wx.toast({ title: '支付失败', icon: 'error' })
    }
  },

  // 生命周期函数--监听页面加载
  onLoad: function (options) {
    this.setData({
      ...options
    })
  },

  // 生命周期函数--监听页面显示
  onShow: function () {
    this.getOrderAddress()
    // 订单详情
    this.getOrderDetail()
  }
})
